package com.hqbzl.c1;


import java.io.*;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class HttpUtils {
    public static void down1() {
        final ArrayList<String> objects = new ArrayList<>();
        try {
            URL url = new URL("http://www.baidu.com");
            URLConnection connection = url.openConnection();
            HttpURLConnection hc = (HttpURLConnection) connection;

            try (final InputStream inputStream = connection.getInputStream()) {
                final BufferedInputStream buffer = new BufferedInputStream(inputStream);
                final InputStreamReader isr = new InputStreamReader(buffer);
                final BufferedReader bufferedReader = new BufferedReader(isr);
                int c = 0;
                while (((c = isr.read()) != -1)) {
                    System.out.print((char) c);
                }
            } catch (Exception e) {

            }
        } catch (Exception e) {
        }
        System.out.println("objects.size() = " + objects.size());
    }

    public static void downList() {
        final ArrayList<String> objects = new ArrayList<>();
        try {
            URL url = new URL("http://www.baidu.com");
            URLConnection connection = url.openConnection();
            final InputStream inputStream = connection.getInputStream();
            final InputStreamReader isr = new InputStreamReader(inputStream);
            final BufferedReader bufferedReader = new BufferedReader(isr);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                objects.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("objects = " + objects.size());
    }

    public static String down() {
        try {
            URL url = new URL("https://github.com/cronie-crond/cronie");
            URLConnection connection = url.openConnection();
            try (final InputStream inputStream = connection.getInputStream()) {
                final byte[] bytes = inputStream.readAllBytes();
                final ByteBuffer allocate = ByteBuffer.allocateDirect(bytes.length);
                allocate.put(bytes);
                allocate.flip();
                final CharBuffer decode = StandardCharsets.UTF_8.decode(allocate);
                return decode.toString();
            } catch (Exception e) {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println("down() = " + down());
    }
}
